/* 
  安装encryptlong，执行以下命令
  npm i encryptlong -S
  引入encryptlong实现数据RSA加密 
  */
import EncryptLong from 'encryptlong' // encryptlong是基于jsencrypt扩展的长文本分段加解密功能。

// 密钥对生成地址 http://web.chacuo.net/netrsakeypair

// 私钥key
const PRIVATE_KEY_FOR_CONFIG = `
-----BEGIN PRIVATE KEY-----
MIICXgIBAAKBgQDKX1Fs2JUD25zrAEwPnjnZC0azrl1XjGzGrJ64eb1lr9QVVOO2
zGKZdqDLZD4Ut4Mp6GHMaqqFXKm+zN7IAXu+mqZbUrqUziHE5YGC02wObiZEzfa6
V9a8ZvqpB+Z8KO+hAkkjzjMl+E+hDORpZmez3SMzetn7mcCeLw8/vmxz3QIDAQAB
AoGBAJBr6b4V6nJwXdHPyngy4PGl/HTqcK60BkTamALqzmEtU9tNU5z2yz7dy+6a
wTsjo7Vao8CwNrUp5fHGXw65EEc1/3Iu2Fiix0XF7RP4NFSoxbBmzQW1nUK/5DFi
4VR1uhEmdbgLwGabsdqzeUqhRKkRGAPVCotBjaDBOu0J3Mu5AkEA+SM7Ctu7evOv
ZwjWrp9a5MGxJ9yLLabbIuWL+420jr2G6ojaTZ2ROA2DWWQPx4JqWxDHttomrb38
dk2emP2WAwJBAM/yU58YRQ+dTeuTzNYC1JdWcs35n9+hoVP7y+x29CmcqDTPp3nR
Bbbq88yMb2nZdlwthWi7BurNHsRJFqj0GJ8CQF5gJCuW1UxcJ2PGi1yW7R2e6fcJ
qoden8B2aDKgmXdBAGyz7s5cE/jB1bH1H60aECPzFVSFCwXh5FMEUEHwPfUCQQC7
JqZ57lbhebrSRcA58GwzFFvY40wu8gIHWvwqgti2xsZgWW+qZCPXf9gSBWaUhmJP
Da0fGAxesGN7VyhswNuTAkEAzCFNqL/zwHXcwh9YyHTdk/bRWIJq49jTA+vbgGv0
szKIvGRKoRbub3NEUiI80TDsCAvbJ6R80J7RjnpmShOwcA==
-----END PRIVATE KEY-----`

// 公钥key
const PUBLIC_KEY_FOR_CONFIG = `
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKX1Fs2JUD25zrAEwPnjnZC0az
rl1XjGzGrJ64eb1lr9QVVOO2zGKZdqDLZD4Ut4Mp6GHMaqqFXKm+zN7IAXu+mqZb
UrqUziHE5YGC02wObiZEzfa6V9a8ZvqpB+Z8KO+hAkkjzjMl+E+hDORpZmez3SMz
etn7mcCeLw8/vmxz3QIDAQAB
-----END PUBLIC KEY-----`

/* 加密 */
function encryptRSA(data: string | number | boolean, key?: any) {
  const PUBLIC_KEY = PUBLIC_KEY_FOR_CONFIG || key
  let encryptor = new EncryptLong()
  encryptor.setPublicKey(PUBLIC_KEY)
  // 如果是对象/数组的话，需要先JSON.stringify转换成字符串
  if (typeof data != 'string') data = JSON.stringify(data)
  let result = encryptor.encryptLong(encodeURIComponent(data))
  return result
}
/* 解密 - PRIVATE_KEY - 验证 */
function decryptRSA(data: any, key?: any) {
  const PRIVATE_KEY = PRIVATE_KEY_FOR_CONFIG || key
  let encryptor = new EncryptLong()
  encryptor.setPrivateKey(PRIVATE_KEY)
  // 如果是对象/数组的话，需要先JSON.stringify转换成字符串
  let result = decodeURIComponent(encryptor.decryptLong(data))
  if (result.startsWith('{') || result.startsWith('[')) {
    try {
      result = JSON.parse(result)
    } catch {}
  }
  // console.log('解密结果',result);

  return result
}

export { encryptRSA, decryptRSA }
